var Rson = require('Rson');
var SpriteLoader = require('RaiSpriteLoader');

var Chess = cc.Class({
    extends: cc.Component,
    
    statics: {
        nf_no1: null,
        nf_no2: null
    },
    
    properties: {
        group: 'G',
        type: 'link',
        grpNum: 0,
        posX: 1,
        posY: 8,
        hasLineBoost: false,
        hasLocked: false,
        isSwitching: false,
        checked: false,
        hasWormDifussion: false,
        hasSandBox: false,
        lockOn: cc.Prefab,
        switchTag: cc.Prefab,
        lineBoost: cc.Prefab,
        wormTag: cc.Prefab,
        checkTag: cc.Prefab,
        sandBoxTag: cc.Prefab,
    },

    // use this for initialization
    onLoad: function () {
        this.canvas = cc.find('Canvas').getComponent('HelloWorld');
        //缓存pfb
        this.pfbList = [];

        let lb = cc.instantiate(this.lineBoost);
        this.node.addChild(lb);
        lb.active = false;
        this.pfbList['lb'] = lb;

        let lock = cc.instantiate(this.lockOn);
        this.node.addChild(lock);
        lock.active = false;
        this.pfbList['lock'] = lock;

        let checkTag = cc.instantiate(this.checkTag);
        this.node.addChild(checkTag);
        checkTag.active = false;
        this.pfbList['check'] = checkTag;

        let sb = cc.instantiate(this.sandBoxTag);
        this.node.addChild(sb);
        sb.active = false;
        this.pfbList['sb'] = sb;

        cc.loader.loadRes("Prefab/switchTag", (err, pfb) => {
            let switchPfb = cc.instantiate(pfb);
            this.node.addChild(switchPfb);
            switchPfb.active = false;
            this.pfbList['404'] = switchPfb;
        });
    },

    // 指定棋子移动到棋盘某格
    // @x:　目标位置的ｘ坐标（棋盘）
    // @ｙ:　目标位置的ｙ坐标（棋盘）
    moveTo: function(x, y){
        let posx, posy;
        this.posX = x;
        this.posY = y;
        if(y == 0){
            if(x<=2)
                posx = 319 - 80*x;
            else if(x<=5)
                posx = 159 - 78.75*(x - 2);
            else
                posx = -156 - 80*(x - 6);
            posy = 325.7;
        }else if(y == 9){
            if(x<=2)
                posx = -316 + 80*x;
            else if(x<=5)
                posx = -156 + 78.75*(x - 2);
            else
                posx = 159 + 80*(x - 6);
            posy = -328;
        }else if(y == -1){
            this.node.setLocalZOrder(1);
            // posx = -313 + 80*x;
            // posy = 370;
            posx = 0;posy = 500;
        }else if(y == 10){
            this.node.setLocalZOrder(1);
            // posx = 318 - 80*x;
            // posy =  -370;
            posx = 0;posy = -500;
        }else{
            posx = -313 + 70*x;
            posy = 315 - 70*y;
        }
        let moveAction = cc.moveTo(0.4, cc.p(posx, posy));
        moveAction.easing(cc.easeIn(0.5));
        this.node.runAction(moveAction);
    },

    // 改变棋子类型
    // @type: 指定棋子类型，有'virus'，'link'和'bottom'三种类型
    // @changeCheckTag：是否改变查验状态标记，默认为是
    changeType: function(type, changeCheckTag = true){
        cc.log('changeType'+type+this.type);
        if(this.type == type)
            return;
        this.type = type;
        //根据翻面状态设置是否已被查验
        if(changeCheckTag)
        {
            if(type == 'bottom')
                this.checked = false;
            else
                this.checked = true;
        }
        //加载图片
        let typeName = this.group + type;
        let rotate1 = cc.scaleTo(0.1, 0, 1);
        let call = ()=>
        {
            SpriteLoader.load(typeName, sprite => {
                cc.log('change typeName:'+typeName);
                this.getComponent(cc.Sprite).spriteFrame = sprite;
            });
        };
        let rotate2 = cc.scaleTo(0.1, 1, 1);
        let seq = cc.sequence(rotate1, cc.callFunc(call), rotate2);

        this.node.runAction(seq);
        //装备有sandbox时
        if(this.hasSandBox)
        {
            let sbNode = this.pfbList['sb'];
            this.updateSandBoxStatusIcon(sbNode);
        }
    },
    
    // 立刻改变棋子类型
    // @type: 指定棋子类型，有'virus'，'link'和'bottom'三种类型
    // @changeCheckTag：是否改变查验状态标记，默认为是
    changeTypeImmediately: function(type, changeCheckTag = true){

        if(this.type == type)
            return;
        this.type = type;
        //根据翻面状态设置是否已被查验
        if(changeCheckTag)
        {
            if(type == 'bottom')
                this.checked = false;
            else
                this.checked = true;
        }
        //加载图片
        let typeName = this.group + type;
        SpriteLoader.load(typeName, sprite => {
            this.getComponent(cc.Sprite).spriteFrame = sprite;
        });
    },

    // 改变棋子阵营/组
    // @group: 指定棋子组别， 有G、B两种类型。指定后会改变棋子纹理图片为对应组的背面（无身份）纹理
    changeGroup: function(group){
        this.group = group;
        SpriteLoader.load(group+'bottom', sprite => {
            this.getComponent(cc.Sprite).spriteFrame = sprite;
        });
    },


    // 以贝赛尔曲线轨迹进行移动
    // @time: 动作持续时间，默认为两秒
    bezierMove: function(time){
        var time =  arguments[1] ? arguments[1] : 2;

        var x = this.node.x;
        var y = this.node.y;
        var lenB = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
        var lenC = Math.sqrt((Math.pow(x,2)+Math.pow(y,2))/3);
        var lenA = lenC * 2;
        var lenD = lenB * 4 / 3;
        var rotation = Math.atan2(-y, -x);
        var ptA = cc.p(lenA * Math.cos(rotation+6/Math.PI) + x, lenA * Math.sin(rotation+6/Math.PI) + y);
        var ptD = cc.p(lenD * Math.cos(rotation) + x, lenD * Math.sin(rotation) + y);

        var bezier = [ptA, ptD,  cc.p(0, 0)];
        var bezierTo = cc.bezierTo(time, bezier);

        return bezierTo;
    },

    // 添加LB选择侦听
    addLBEvent: function(){
        this.setLockTag(true);

        this.node.on('touchend', (event)=>{
            this.node.targetOff(this.node);

            let cmd = Rson.encode({'code':'32', 'name':'LBChoose', data:{'no': this.grpNum}});
            cc.log(cmd);
            cc.webSocket.send(cmd);
        }, this.node);
    },

    // 添加VC选择侦听
    addVCEvent: function(){
        this.setLockTag(true);

        this.node.on('touchend', (event)=>{
            this.node.targetOff(this.node);

            let cmd = Rson.encode({'code':'52', 'name':'VCChoose', data:{'no': this.grpNum}});
            cc.log(cmd);
            cc.webSocket.send(cmd);
        }, this.node);
    },

    // 添加NF选择侦听
    addNFEvent: function(){
        this.setLockTag(true);

        this.node.on('touchend', (event)=>{
            this.node.targetOff(this.node);
            this.setLockTag(false);
            this.setSwitchTag(true);

            if(!Chess.nf_no1)
                Chess.nf_no1 = this.grpNum;
            else if(!Chess.nf_no2)
            {
                Chess.nf_no2 = this.grpNum;
                let main = cc.find('Canvas').getComponent('HelloWorld');
                main.showPop('switch');
            }
        }, this.node);
    },

    // 添加ZDA选择侦听
    addZDAEvent: function(){
        this.setLockTag(true);

        this.node.on('touchend', (event)=>{
            this.node.targetOff(this.node);

            let cmd = Rson.encode({'code':'211', 'name':'ZDAChoose', data:{'chessNo': this.grpNum}});
            cc.log(cmd);
            cc.webSocket.send(cmd);
        }, this.node);
    },

    // 添加SB选择侦听
    addSBEvent: function(){
        this.setLockTag(true);

        this.node.on('touchend', (event)=>{
            this.node.targetOff(this.node);

            let cmd = Rson.encode({'code':'231', 'name':'SBChoose', data:{'selectGroup': this.group, 'chessNo': this.grpNum}});
            cc.log(cmd);
            cc.webSocket.send(cmd);
        }, this.node);
    },

    // 清除所有选中图标
    clearFocusTag: function(){
        // cc.log('清除选中图标');

        this.setLockTag(false);
        this.setSwitchTag(false);
    },

    clearAllTag: function(exceptStr = ''){
        cc.log('清除所有图标');
        
        this.setLockTag(false);
        if(exceptStr.indexOf('404') < 0)
            this.setSwitchTag(false);
        if(exceptStr.indexOf('check') < 0)
            this.setCheckTag(false);
        if(exceptStr.indexOf('lb') < 0)
            this.setLineBoost(false);
        if(exceptStr.indexOf('sb') < 0)
            this.setSandBox(false);
    },

    // 设置/解除加速回线
    // @judge: 加速回线的开关，true为开启， false为关闭
    // tag: 12
    setLineBoost: function(judge){
        cc.log('setLineBoost', judge, this.hasLineBoost);
        if(judge && !this.hasLineBoost){
            this.hasLineBoost = true;
            this.pfbList['lb'].active = true;

        }else if(!judge && this.hasLineBoost){
            this.hasLineBoost = false;
            this.pfbList['lb'].active = false;
        }
    },

    // 设置/解除锁定状态
    // 锁定状态为对方棋子处于我方攻击范围内时的状态
    // @judge: 锁定开关，true为开启， false为关闭
    // tag: 10
    setLockTag: function(judge){
        cc.log('setLockTag', judge, this.hasLocked);
        if(judge && !this.hasLocked){
            this.hasLocked = true;
            this.pfbList['lock'].active = true;

        }else if(!judge && this.hasLocked){
            this.hasLocked = false;
            this.pfbList['lock'].active = false;
        }
    },

    // 设置/解除待交换状态
    // 锁定状态为我方棋子处于交换模式被选择时的状态
    // @judge: 锁定开关，true为开启， false为关闭
    // tag: 404
    setSwitchTag: function(judge){
        cc.log('setSwitchTag', judge, this.isSwitching);
        if(judge && !this.isSwitching){
            this.isSwitching = true;
            this.pfbList['404'].active = true;

        }else if(!judge && this.isSwitching){
            this.isSwitching = false;
            this.pfbList['404'].active = false;
        }
    },

    // 设置/解除查杀状态
    // 查杀状态为我方棋子处于被对方使用virus check后的状态
    // @judge: 开关，true为开启， false为关闭
    // tag: 1
    setCheckTag: function(judge){
        cc.log('setCheckTag', judge, this.checked);
        if(this.checked == judge)
            return;
        this.checked = judge;

        if(judge){
            this.pfbList['check'].active = true;
            //装备有sandbox时
            if(this.hasSandBox)
            {
                let sbNode = this.pfbList['sb'];
                this.updateSandBoxStatusIcon(sbNode);
            }
        }else
            this.pfbList['check'].active = false;
    },

    // 设置沙盒测试
    // tag: 15
    setSandBox: function(judge){
        cc.log('setSandBoxTest', judge, this.hasSandBox);
        if(judge && !this.hasSandBox){
            this.hasSandBox = true;
            let sbNode = this.pfbList['sb'];
            sbNode.active = true;
            this.updateSandBoxStatusIcon(sbNode);

        }else if(!judge && this.hasSandBox){
            this.hasSandBox = false;
            this.pfbList['sb'].active = false;
        }
    },

    //刷新sandbox状态图标
    updateSandBoxStatusIcon: function(node){
        if(node == null || !node.active)
            return;
        let sp = node.getComponent(cc.Sprite);
        if(!this.checked)
        {
            SpriteLoader.load('sandboxUnlock', sprite => {
                sp.spriteFrame = sprite;
            });
        }
        else if(this.type == 'virus')
        {
            SpriteLoader.load('sandboxLock', sprite => {
                sp.spriteFrame = sprite;
            });
        }
        else if(this.type == 'link')
        {
            SpriteLoader.load('sandboxUnlock2', sprite => {
                sp.spriteFrame = sprite;
            });
        }
    },

    //设置定时销毁的特效
    setTempEffect: function(obj, time, posX = 0, posY = 0)
    {
        this.node.addChild(obj);
        obj.setPosition(posX, posY);
        //一定时间后销毁特效对象
        this.schedule(function(){
            this.node.removeChild(obj);
        }, time);
    },
});
